<template>
  <view class="page_form_wrap">
    <view class="title_wrap">基本信息</view>
    <view class="content_wrap">
      <view class="item_wrap">
        <view class="label_wrap"><text>*</text>货源名称</view>
        <view class="value_wrap">
          <input v-model="formData.goodsSourceName" :maxlength="50" placeholder="请输入货源名称" />
        </view>
      </view>
      <view class="item_wrap">
        <view class="label_wrap"><text>*</text>联系电话</view>
        <view class="value_wrap">
          <input v-model="formData.consignorPhone" type="tel" :maxlength="11" placeholder="请输入联系电话" />
        </view>
      </view>
      <view v-if="purchaserId" class="item_wrap">
        <view class="label_wrap"><text>*</text>装货地</view>
        <view class="value_wrap">
          <view><input v-model="formData.loadingPlaceName" :disabled="true" placeholder="请选择装货地"
              @click="openSelectPop('loading')" /></view>
          <uni-icons type="forward" size="20" color="#999999"></uni-icons>
        </view>
      </view>
      <view v-if="cusId" class="item_wrap">
        <view class="label_wrap"><text>*</text>装货地</view>
        <view class="value_wrap">
          <input v-model="formData.loadingPlaceName" :disabled="true" placeholder="请选择装货地" />
        </view>
      </view>
      <view class="item_wrap">
        <view class="label_wrap"><text>*</text>卸货地</view>
        <view class="value_wrap">
          <view><input v-model="formData.unloadingPlaceName" :disabled="true" placeholder="请选择卸货地"
              @click="openSelectPop('unloading')" /></view>
          <uni-icons type="forward" size="20" color="#999999"></uni-icons>
        </view>
      </view>
      <view class="item_wrap">
        <view class="label_wrap"><text>*</text>产品</view>
        <view class="value_wrap">
          <view><input v-model="formData.productName" :disabled="true" placeholder="请选择产品"
              @click="openSelectPop('product')" /></view>
          <uni-icons type="forward" size="20" color="#999999"></uni-icons>
        </view>
      </view>
      <view class="item_wrap">
        <view class="label_wrap"><text>*</text>开始时间</view>
        <view class="value_wrap">
          <view><uni-datetime-picker v-model="formData.startTime" type="datetime" placeholder="请选择开始时间" /></view>
          <uni-icons type="forward" size="20" color="#999999"></uni-icons>
        </view>
      </view>
      <view class="item_wrap">
        <view class="label_wrap"><text>*</text>结束时间</view>
        <view class="value_wrap">
          <view><uni-datetime-picker v-model="formData.endTime" type="datetime" placeholder="请选择结束时间" /></view>
          <uni-icons type="forward" size="20" color="#999999"></uni-icons>
        </view>
      </view>
    </view>
    <view class="title_wrap">运输信息</view>
    <view class="content_wrap">
      <view class="item_wrap">
        <view class="label_wrap"><text>*</text>运价</view>
        <view class="value_wrap">
          <view><input v-model="formData.freight" type="digit" :maxlength="9" placeholder="请输入运价" /></view>
          <text>元/吨</text>
        </view>
      </view>
      <view class="item_wrap">
        <view class="label_wrap"><text>*</text>结算依据</view>
        <view class="value_wrap">
          <view>
            <picker @change="handleSettlementBasis" :value="settlementBasisIndex" mode="selector"
              :range="settlementBasisList" range-key="label">
              <input v-model="settlementBasisText" :disabled="true" placeholder="请选择结算依据" />
            </picker>
          </view>
          <uni-icons type="forward" size="20" color="#999999"></uni-icons>
        </view>
      </view>
      <view class="item_wrap">
        <view class="label_wrap"><text>*</text>是否计算路损</view>
        <view class="value_wrap">
          <view>
            <picker @change="handleIsCalculateRoadLoss" :value="isCalculateRoadLossIndex" mode="selector"
              :range="isCalculateRoadLossList" range-key="label">
              <input v-model="isCalculateRoadLossText" :disabled="true" placeholder="请选择是否计算路损" />
            </picker>
          </view>
          <uni-icons type="forward" size="20" color="#999999"></uni-icons>
        </view>
      </view>
      <view v-if="formData.isCalculateRoadLoss==='0'" class="item_wrap">
        <view class="label_wrap"><text>*</text>合理路损</view>
        <view class="value_wrap">
          <view><input v-model="formData.reasonableRoadLoss" type="digit" :maxlength="9" placeholder="请输入合理路损" />
          </view>
          <text>吨</text>
        </view>
      </view>
      <view v-if="formData.isCalculateRoadLoss==='0'" class="item_wrap">
        <view class="label_wrap"><text>*</text>路损单价</view>
        <view class="value_wrap">
          <view><input v-model="formData.roadLossPrice" type="digit" :maxlength="9" placeholder="请输入路损单价" /></view>
          <text>元</text>
        </view>
      </view>
      <view v-if="formData.isCalculateRoadLoss==='0'" class="item_wrap">
        <view class="label_wrap">路损计算规则</view>
        <view class="value_wrap">
          <view>
            <picker @change="handleRoadLossCalculateRule" :value="roadLossCalculateRuleIndex" mode="selector"
              :range="roadLossCalculateRuleList" range-key="label">
              <input v-model="roadLossCalculateRuleText" :disabled="true" placeholder="请选择路损计算规则" />
            </picker>
          </view>
          <uni-icons type="forward" size="20" color="#999999"></uni-icons>
        </view>
      </view>
      <view class="item_wrap">
        <view class="label_wrap"><text>*</text>抹零规则</view>
        <view class="value_wrap">
          <view>
            <picker @change="handleErasureRule" :value="erasureRuleIndex" mode="selector" :range="erasureRuleList"
              range-key="label">
              <input v-model="erasureRuleText" :disabled="true" placeholder="请选择抹零规则" />
            </picker>
          </view>
          <uni-icons type="forward" size="20" color="#999999"></uni-icons>
        </view>
      </view>
      <view class="item_wrap">
        <view class="label_wrap">备注</view>
        <view class="value_wrap">
          <input v-model="formData.remark" :maxlength="100" placeholder="请输入" />
        </view>
      </view>
    </view>
    <view class="footer_wrap">
      <button v-if="findCarOnPlatformBtn==='1'" type="primary" :disabled="isDisabled"
        @click="submitSourceForm">提交</button>
      <button v-if="viewGoodsSourceBtn==='1'" type="primary" plain="true" :disabled="isDisabled"
        @click="closeGoodsSourceFn">关闭货源</button>
      <button v-if="viewGoodsSourceBtn==='1'" :disabled="isDisabled" @click="submitSourceForm">更新货源</button>
    </view>
    <select-search ref="selectSearchRef" :title="popTitle" :show="isShow" :name="searchName" :param="paramValue"
      :value="searhValue" :type="'radio'" :dataLists="list" @search="searchFn" @cancel="isShow = false"
      @submit="submitSelectFn"></select-search>
    <success-pop :show="isSuccessShow" :isUpdate="formData.id" :phoneNum="phoneNum"
      @closePop="isSuccessShow=false"></success-pop>
  </view>
</template>

<script>
  import config from '@/config';
  import { toast } from '@/utils/common';
  import successPop from '../common/success-pop'
  import { getDictList } from '@/api/login';
  import { createGoodsSource, updateGoodsSource, closeGoodsSource, getGoodsSourceByPlanId, getLoadLists, getProductByPurchaserId, getAddress, getTransportDetail } from '@/api/goodsSource.js';
  import { findProCusRelName, findcusAddressbyCusId } from '@/api/tranplan.js';
  export default {
    components: {
      successPop
    },
    data() {
      return {
        isShow: false,
        isSuccessShow: false,
        isDisabled: false,
        selectType: undefined,
        searchName: 'label',
        searhValue: 'value',
        popTitle: '选择装货地',
        list: [],
        loadingList: [],
        unloadingList: [],
        productList: [],
        settlementBasisList: [],
        isCalculateRoadLossList: [],
        roadLossCalculateRuleList: [],
        erasureRuleList: [],
        phoneNum: undefined,
        cusId: undefined,
        purchaserId: undefined,
        viewGoodsSourceBtn: undefined,
        findCarOnPlatformBtn: undefined,
        settlementBasisIndex: 0,
        isCalculateRoadLossIndex: 0,
        roadLossCalculateRuleIndex: 0,
        erasureRuleIndex: 0,
        paramValue: undefined,
        formData: {
          id: undefined,
          planId: undefined,
          planNo: undefined,
          bizType: undefined,
          goodsSourceName: undefined,
          startTime: undefined,
          endTime: undefined,
          productId: undefined,
          productName: undefined,
          consignorPhone: undefined,
          loadingPlaceId: undefined,
          loadingPlaceName: undefined,
          unloadingPlaceId: undefined,
          unloadingPlaceName: undefined,
          freight: undefined,
          settlementBasis: undefined,
          isCalculateRoadLoss: undefined,
          reasonableRoadLoss: undefined,
          roadLossPrice: undefined,
          roadLossCalculateRule: undefined,
          erasureRule: undefined,
          remark: undefined
        }
      };
    },
    computed: {
      settlementBasisText() {
        return this.settlementBasisList.find(e => e.value === this.formData.settlementBasis)?.label
      },
      isCalculateRoadLossText() {
        return this.isCalculateRoadLossList.find(e => e.value === this.formData.isCalculateRoadLoss)?.label
      },
      roadLossCalculateRuleText() {
        return this.roadLossCalculateRuleList.find(e => e.value === this.formData.roadLossCalculateRule)?.label || ''
      },
      erasureRuleText() {
        return this.erasureRuleList.find(e => e.value === this.formData.erasureRule)?.label
      },
    },
    onLoad(options) {
      this.formData.planId = options.id
      this.formData.planNo = options.planNo
      this.formData.bizType = options.bizType
      this.cusId = options.cusId
      this.purchaserId = options.purchaserId
      this.viewGoodsSourceBtn = options.viewGoodsSourceBtn
      this.findCarOnPlatformBtn = options.findCarOnPlatformBtn
    },
    async onShow() {
      await this.getDictLists()
      if (this.purchaserId) {
        await this.getLoadSitePages(this.purchaserId, 1)
        await this.getLoadSitePages(this.purchaserId, 2)
        await this.getProductByPurchaserId(this.purchaserId)
      }
      if (this.cusId) {
        await this.getAddress()
        await this.findcusAddressbyCusId(this.cusId)
        await this.findProCusRelName(this.cusId)
      }
      if (this.viewGoodsSourceBtn === '1') {
        this.getGoodsSourceByPlanId(this.formData.planId)
      }
      if (this.findCarOnPlatformBtn === '1' && this.formData.bizType === '1') {
        this.getTransportDetail()
      }
    },
    methods: {
      async getDictLists() {
        const res = await getDictList();
        if (res.code === 0) {
          this.settlementBasisList = (res.data || []).filter(
            (e) => e.dictType === 'settlement_basis'
          );
          this.isCalculateRoadLossList = (res.data || []).filter(
            (e) => e.dictType === 'is_calculate_road_loss'
          );
          this.roadLossCalculateRuleList = (res.data || []).filter(
            (e) => e.dictType === 'road_loss_calculate_rule'
          );
          this.erasureRuleList = (res.data || []).filter(
            (e) => e.dictType === 'erasure_rule'
          );
          this.phoneNum = (res.data || []).filter(
            (e) => e.dictType === 'contact_number'
          )[0]?.label;
        }
      },
      async getLoadSitePages(id, type) {
        const res = await getLoadLists({ id, type })
        if (res.code !== 0) {
          this.loadingList = []
          this.unloadingList = []
          toast(res.msg)
          return
        }
        if (type === 1) {
          this.loadingList = res.data || []
        }
        if (type === 2) {
          this.unloadingList = res.data || []
        }
      },
      async getAddress() {
        const res = await getAddress()
        if (res.code === 0) {
          this.formData.loadingPlaceName = res.data
        }
      },
      async findcusAddressbyCusId(cusId) {
        const res = await findcusAddressbyCusId({ cusId })
        if (res.code === 0) {
          const result = res.data || []
          this.unloadingList = result.map(e => {
            return {
              id: e.id,
              siteName: e.cusAddress
            }
          })
        } else {
          toast(res.msg)
        }
      },
      async findProCusRelName(cusId) {
        const res = await findProCusRelName({ cusId })
        if (res.code === 0) {
          const result = res.data || []
          this.productList = result.map(e => {
            return {
              id: e.proId,
              productName: e.proName
            }
          })
        } else {
          toast(res.msg)
        }
      },
      async getProductByPurchaserId(purchaserId) {
        const res = await getProductByPurchaserId({ purchaserId })
        if (res.code === 0) {
          this.productList = res.data || []
        } else {
          toast(res.msg)
        }
      },
      async getTransportDetail() {
        const res = await getTransportDetail(this.formData.planId)
        if (res.code === 0) {
          if (res.data?.proId) {
            this.formData.productId = res.data?.proId
            this.formData.productName = this.productList.find(e => e.id === res.data?.proId)?.productName
          }
          if (![undefined, null].includes(res.data?.loadingSiteId)) {
            this.formData.loadingPlaceId = res.data?.loadingSiteId
            this.formData.loadingPlaceName = this.loadingList.find(e => e.id === res.data?.loadingSiteId)?.siteName
          }
          if (![undefined, null].includes(res.data?.landingPlaceId)) {
            this.formData.unloadingPlaceId = res.data?.landingPlaceId
            this.formData.unloadingPlaceName = this.unloadingList.find(e => e.id === res.data?.landingPlaceId)?.siteName
          }
          if (res.data?.startTime) {
            this.formData.startTime = res.data?.startTime
          }
          if (res.data?.endTime) {
            this.formData.endTime = res.data?.endTime
          }
          if (![undefined, null].includes(res.data?.freight)) {
            this.formData.freight = res.data?.freight
          }
          if (![undefined, null].includes(res.data?.reasonableRoadLoss)) {
            this.formData.reasonableRoadLoss = res.data?.reasonableRoadLoss
          }
          if (![undefined, null].includes(res.data?.roadLossPrice)) {
            this.formData.roadLossPrice = res.data?.roadLossPrice
          }
          if (![undefined, null].includes(res.data?.settlementBasis)) {
            this.formData.settlementBasis = res.data?.settlementBasis?.toString()
            this.settlementBasisIndex = this.settlementBasisList.findIndex(e => e.value === this.formData.settlementBasis?.toString())
          }
          if (![undefined, null].includes(res.data?.isCalculateRoadLoss)) {
            this.formData.isCalculateRoadLoss = res.data?.isCalculateRoadLoss?.toString()
            this.isCalculateRoadLossIndex = this.isCalculateRoadLossList.findIndex(e => e.value === this.formData.isCalculateRoadLoss?.toString())
          }
          if (this.formData.isCalculateRoadLoss === '0' && ![undefined, null].includes(res.data?.roadLossCalculateRule)) {
            this.formData.roadLossCalculateRule = res.data?.roadLossCalculateRule?.toString()
            this.roadLossCalculateRuleIndex = this.roadLossCalculateRuleList.findIndex(e => e.value === this.formData.roadLossCalculateRule?.toString())
          }
          if (![undefined, null].includes(res.data?.erasureRule)) {
            this.formData.erasureRule = res.data?.erasureRule?.toString()
            this.erasureRuleIndex = this.erasureRuleList.findIndex(e => e.value === this.formData.erasureRule?.toString())
          }
        }
      },
      async getGoodsSourceByPlanId(planId) {
        const res = await getGoodsSourceByPlanId({ planId })
        if (res.code === 0) {
          const result = res.data || {}
          Object.keys(this.formData).forEach(key => {
            if (['settlementBasis', 'isCalculateRoadLoss', 'roadLossCalculateRule', 'erasureRule'].includes(key)) {
              this.formData[key] = result[key]?.toString()
            } else {
              this.formData[key] = result[key]
            }
          })
          if (this.formData.productId) {
            this.formData.productName = this.productList.find(e => e.id === this.formData.productId)?.productName
          }
          if (this.purchaserId && this.formData.loadingPlaceId) {
            this.formData.loadingPlaceName = this.loadingList.find(e => e.id == this.formData.loadingPlaceId)?.siteName
          }
          if (this.cusId) {
            this.getAddress()
          }
          if (this.formData.unloadingPlaceId) {
            this.formData.unloadingPlaceName = this.unloadingList.find(e => e.id == this.formData.unloadingPlaceId)?.siteName
          }
          this.settlementBasisIndex = this.settlementBasisList.findIndex(e => e.value === this.formData.settlementBasis?.toString())
          this.isCalculateRoadLossIndex = this.isCalculateRoadLossList.findIndex(e => e.value === this.formData.isCalculateRoadLoss?.toString())
          this.roadLossCalculateRuleIndex = this.roadLossCalculateRuleList.findIndex(e => e.value === this.formData.roadLossCalculateRule?.toString())
          this.erasureRuleIndex = this.erasureRuleList.findIndex(e => e.value === this.formData.erasureRule?.toString())
        } else {
          toast(res.msg)
        }
      },
      handleSettlementBasis({ detail }) {
        this.settlementBasisIndex = detail.value
        this.formData.settlementBasis = this.settlementBasisList[this.settlementBasisIndex].value
      },
      handleIsCalculateRoadLoss({ detail }) {
        this.isCalculateRoadLossIndex = detail.value
        this.formData.isCalculateRoadLoss = this.isCalculateRoadLossList[this.isCalculateRoadLossIndex].value
        if (this.formData.isCalculateRoadLoss === '1') {
          this.formData.roadLossCalculateRule = undefined
          this.formData.reasonableRoadLoss = undefined
          this.formData.roadLossPrice = undefined
        }
      },
      handleRoadLossCalculateRule({ detail }) {
        this.roadLossCalculateRuleIndex = detail.value
        this.formData.roadLossCalculateRule = this.roadLossCalculateRuleList[this.roadLossCalculateRuleIndex].value
      },
      handleErasureRule({ detail }) {
        this.erasureRuleIndex = detail.value
        this.formData.erasureRule = this.erasureRuleList[this.erasureRuleIndex].value
      },
      openSelectPop(type) {
        this.selectType = type
        this.searchName = 'siteName'
        this.searhValue = 'id'
        if (type === 'loading') {
          this.popTitle = '选择装货地'
          this.list = JSON.parse(JSON.stringify(this.loadingList))
          this.paramValue = this.formData.loadingPlaceId ? Number(this.formData.loadingPlaceId) : undefined
        }
        if (type === 'unloading') {
          this.popTitle = '选择卸货地'
          this.list = JSON.parse(JSON.stringify(this.unloadingList))
          this.paramValue = this.formData.unloadingPlaceId
          if (this.purchaserId) {
            this.paramValue = this.formData.unloadingPlaceId ? Number(this.formData.unloadingPlaceId) : undefined
          }
        }
        if (type === 'product') {
          this.popTitle = '选择产品'
          this.searchName = 'productName'
          this.searhValue = 'id'
          this.list = JSON.parse(JSON.stringify(this.productList))
          this.paramValue = this.formData.productId
        }
        this.isShow = true
      },
      searchFn(keyword) {
        let list = []
        switch (this.selectType) {
          case 'loading':
            list = JSON.parse(JSON.stringify(this.loadingList))
            this.list = list.filter(e => e.siteName.includes(keyword))
            break;
          case 'unloading':
            list = JSON.parse(JSON.stringify(this.unloadingList))
            this.list = list.filter(e => e.siteName.includes(keyword))
            break;
          case 'product':
            list = JSON.parse(JSON.stringify(this.productList))
            this.list = list.filter(e => e.productName.includes(keyword))
            break;
          default: break
        }

      },
      submitSelectFn(data) {
        switch (this.selectType) {
          case 'loading':
            this.formData.loadingPlaceId = data.id
            this.formData.loadingPlaceName = data.siteName
            break;
          case 'unloading':
            this.formData.unloadingPlaceId = data.id
            this.formData.unloadingPlaceName = data.siteName
            break;
          case 'product':
            this.formData.productId = data.id
            this.formData.productName = data.productName
            break;
          default: break;
        }
        this.isShow = false
      },
      async submitSourceForm() {
        if (!this.formData.goodsSourceName) {
          toast('请输入货源名称')
          return
        }
        if (!this.formData.consignorPhone || !/^\d{8,11}$/.test(this.formData.consignorPhone)) {
          toast('请输入8-11位的联系电话')
          return
        }
        if (this.purchaserId && !this.formData.loadingPlaceId) {
          toast('请选择装货地')
          return
        }
        if (!this.formData.unloadingPlaceId) {
          toast('请选择卸货地')
          return
        }
        if (!this.formData.productId) {
          toast('请选择产品')
          return
        }
        if (!this.formData.startTime) {
          toast('请选择开始时间')
          return
        }
        if (!this.formData.endTime) {
          toast('请选择结束时间')
          return
        }
        const startTimeStamp = new Date(this.formData.startTime).getTime()
        const endTimeStamp = new Date(this.formData.endTime).getTime()
        if (startTimeStamp >= endTimeStamp) {
          toast('开始时间不能晚于或等于结束时间')
          return
        }
        if (!/^\d+(\.\d{1,2})?$/.test(this.formData.freight) || this.formData.freight >= 1000000 || this.formData.freight < 0) {
          toast('请输入0.00-999999.99范围内的运价')
          return
        }
        if (!this.formData.settlementBasis) {
          toast('请选择结算依据')
          return
        }
        if (!this.formData.isCalculateRoadLoss) {
          toast('请选择是否计算路损')
          return
        }
        if (this.formData.isCalculateRoadLoss === '0') {
          if (!/^\d+(\.\d{1,2})?$/.test(this.formData.reasonableRoadLoss) || this.formData.reasonableRoadLoss >= 1000000 || this.formData.reasonableRoadLoss < 0) {
            toast('请输入0.00-999999.99范围内的合理路损')
            return
          }
          if (!/^\d+(\.\d{1,2})?$/.test(this.formData.roadLossPrice) || this.formData.roadLossPrice >= 1000000 || this.formData.roadLossPrice < 0) {
            toast('请输入0.00-999999.99范围内的路损单价')
            return
          }
        }
        if (!this.formData.erasureRule) {
          toast('请选择抹零规则')
          return
        }
        if (this.isDisabled) return
        try {
          this.isDisabled = true
          if (this.formData.id) {
            uni.showModal({
              title: '提示信息',
              content: '确认要更新货源信息？',
              showCancel: true,
              success: async (res) => {
                if (res.confirm) {
                  const res = await updateGoodsSource(this.formData)
                  if (res.code !== 0) {
                    toast(res.msg)
                    return
                  }
                  this.isSuccessShow = true
                }
              }
            });
            return
          }
          const res = await createGoodsSource(this.formData)
          if (res.code !== 0) {
            toast(res.msg)
            return
          }
          this.isSuccessShow = true
        } finally {
          this.isDisabled = false
        }
      },
      async closeGoodsSourceFn() {
        if (this.isDisabled) return
        try {
          this.isDisabled = true
          uni.showModal({
            title: '提示信息',
            content: '确认要关闭货源信息？',
            showCancel: true,
            success: async (res) => {
              if (res.confirm) {
                const res = await closeGoodsSource({
                  id: this.formData.id,
                  bizType: this.formData.bizType,
                  planId: this.formData.planId
                })
                if (res.code === 0) {
                  this.$tab.navigateBack()
                  setTimeout(() => {
                    toast('货源关闭成功')
                  }, 500)
                } else {
                  toast(res.msg)
                }
              }
            }
          });
        } finally {
          this.isDisabled = false
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  ::v-deep .uniui-calendar {
    display: none !important
  }

  ::v-deep .uni-date-x--border {
    border: none !important
  }

  button[type="primary"] {
    background-color: #409eff !important;
  }

  button[disabled] {
    background-color: #409eff !important;
  }

  button[type="primary"][plain] {
    background-color: #ffffff !important;
  }

  .footer_wrap {
    display: flex;

    button {
      flex: 1;
    }

    button+button {
      margin-left: 20rpx;
    }
  }

  @import "@/static/scss/custom_form.scss";
</style>